# **************************************
# --*-- coding: utf-8 --*--
# @Time    : 2023-07-04
# @Author  : white
# @FileName: Log.py
# @Software: PyCharm
# **************************************
import logging
import os
import sys

import colorlog
from concurrent_log_handler import ConcurrentRotatingFileHandler

from .singleton import singleton


# pip install concurrent-log-handler
# pip install colorlog
@singleton
def log():
    console_log_level = logging.INFO  # 控制台日志等级
    file_log_level = logging.DEBUG  # 文件日志等级
    logger = logging.getLogger('mylogger')
    logger.setLevel(logging.DEBUG)
    name = os.path.basename(os.getcwd())
    path = 'log/%s.log' % name
    if not os.path.exists("log"):
        os.mkdir("log")
    date_time_fmt = '%Y-%m-%d|%H:%M:%S'
    fmt = '[%(asctime)s][%(filename)s:%(funcName)s:%(lineno)d] %(levelname)s: %(message)s'
    ################ 控制台日志设置 ##################
    log_colors_config = {
        'DEBUG'   : 'white',  # cyan white
        'INFO'    : 'green',
        'WARNING' : 'yellow',
        'ERROR'   : 'red',
        'CRITICAL': 'bold_red',
    }
    format_console = colorlog.ColoredFormatter(  # 控制台日志控制 添加了颜色控制
        fmt="%(log_color)s" + fmt,
        datefmt=date_time_fmt,
        log_colors=log_colors_config
    )
    console_Handler = logging.StreamHandler(sys.stdout)
    console_Handler.setFormatter(format_console)  # 设置日志格式
    console_Handler.setLevel(console_log_level)  # 设置日志等级
    logger.addHandler(console_Handler)  # 控制台日志
    ################### 文件日志设置 #################
    # 写入文件中日志样式控制
    # 写入文件中控制 备份周期为7天
    # file_handler = handlers.TimedRotatingFileHandler(path, when='midnight', interval=1, backupCount=7,
    #                                                  atTime=datetime.time(0, 0, 0, 0))
    # 多线程日志切割
    file_fmt = logging.Formatter(
        fmt=fmt,
        datefmt=date_time_fmt)
    rotate_Handler = ConcurrentRotatingFileHandler(path, "a", 512 * 1024 * 3, 5)
    rotate_Handler.setFormatter(file_fmt)  # 设置日志格式
    rotate_Handler.setLevel(file_log_level)  # 设置日志等级
    logger.addHandler(rotate_Handler)  # 添加到当前日志处理中
    ##########################################
    return logger


logger = log()
